{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6da3a277",
   "metadata": {},
   "source": [
    "### Consolidation simulation\n",
    "\n",
    "This notebook models consolidation as teacher-student learning, in which initial representations of memories are replayed to train a generative model.\n",
    "\n",
    "#### End-to-end simulation example\n",
    "\n",
    "For the Shapes3D dataset, the following code:\n",
    "* Encodes 10000 images (i.e. memories) in the modern Hopfield network.\n",
    "* Gives the Hopfield network random noise as an input, and gets the outputs (which should be the stored memories). The outputs of this stage are saved in the mhn_memories folder for re-use; to regenerate from scratch delete the contents of the folder.\n",
    "* Trains a variational autoencoder on the 'memories', and tests its recall.\n",
    "* Generates plots of semantic decoding accuracy and reconstruction error over the course of training.\n",
    "* Displays the latent space (projected into 2D and colour coded by class).\n",
    "* Runs a set of other tests, e.g. of interpolation between items.\n",
    "* Saves the outputs to a PDF in the 'outputs' folder, together with the loss history.\n",
    "* Examples of recall in the extended version of the model are saved in the 'hybrid_model' folder."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1ecdfd09",
   "metadata": {},
   "source": [
    "#### Colab installation:\n",
    "\n",
    "Remember to press the 'Restart runtime' button after running the cell below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5cf33f1f",
   "metadata": {},
   "outputs": [],
   "source": [
    "!git clone https://github.com/ellie-as/generative-memory.git\n",
    "%cd /content/generative-memory/\n",
    "!pip install -r requirements.txt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8dae2872",
   "metadata": {},
   "outputs": [],
   "source": [
    "%cd /content/generative-memory\n",
    "\n",
    "import sys\n",
    "sys.path.append('/content/generative-memory')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7875e2c7",
   "metadata": {},
   "source": [
    "#### Local installation:\n",
    "\n",
    "Tested with Tensorflow 2.11.0 and Python 3.10.9."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7f171ba1-ee18-45b7-9a09-f1564b05b47b",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# !pip install -r requirements.txt --upgrade"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "30262f97",
   "metadata": {},
   "source": [
    "#### Results:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "40296a40-1641-4750-aaf2-0f603acc2a4b",
   "metadata": {
    "scrolled": true,
    "tags": []
   },
   "outputs": [],
   "source": [
    "from end_to_end import *\n",
    "from extended_model import *\n",
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "\n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "\n",
    "# set tensorflow and numpy random seeds to make outputs reproducible\n",
    "tf.random.set_seed(123)\n",
    "np.random.seed(123)\n",
    "\n",
    "# set tensorflow image format to arrays of dim (width, height, num_channels)\n",
    "tf.keras.backend.set_image_data_format('channels_last')\n",
    "\n",
    "# set number of epochs (actually the max number as early stopping is enabled)\n",
    "generative_epochs = 50\n",
    "# set number of images\n",
    "num_ims = 10000\n",
    "# set encoding thresholds in extended model\n",
    "threshold_low = 0.03\n",
    "threshold_high = 0.15\n",
    "\n",
    "# dataset specific parameters:\n",
    "params = {\n",
    "    'hopfield_beta': 20,\n",
    "    'latent_dim': 20\n",
    "}\n",
    "\n",
    "dataset = 'shapes3d'\n",
    "\n",
    "# run 'basic' version of model with parameters specified for dataset\n",
    "net, vae = run_end_to_end(dataset=dataset, \n",
    "                          generative_epochs=generative_epochs, \n",
    "                          num=num_ims, \n",
    "                          latent_dim=params['latent_dim'], \n",
    "                          interpolate=True,\n",
    "                          do_vector_arithmetic=True,\n",
    "                          kl_weighting=1,\n",
    "                          lr = 0.001,\n",
    "                          hopfield_beta=params['hopfield_beta'],\n",
    "                          use_weights=True)\n",
    "# plot the stages of recall in the 'extended' model, with the lower error threshold\n",
    "test_extended_model(dataset=dataset, \n",
    "                vae=vae, \n",
    "                latent_dim=params['latent_dim'],\n",
    "                threshold = threshold_low,\n",
    "                n=10)\n",
    "# plot the stages of recall in the 'extended' model, with the higher error threshold\n",
    "test_extended_model(dataset=dataset, \n",
    "                vae=vae, \n",
    "                latent_dim=params['latent_dim'],\n",
    "                threshold = threshold_high,\n",
    "                n=10)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
